package net.airtheva.weather;

import java.util.Iterator;

import net.airtheva.uniqueTask5.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

public class Location {

	public String Name;
	public Weather[] Weathers;
	
	public Location(String name) {
		
		Name = name;
		Weathers = new Weather[6];
		
	}
	
	public void Update(Context context, JSONObject json) {
		
		try {
			JSONObject weatherInfo = json.getJSONObject("weatherinfo");
			
			Iterator<String> i = weatherInfo.keys();
			while(i.hasNext()) {
				String key = i.next();
				
				if(key.equals("city")) {
					Name = weatherInfo.getString("city");
				}
				else if(key.matches("temp\\d")) {
					int index = Integer.parseInt(key.substring(4)) - 1;
					Weather weather = Weathers[index] == null ? Weathers[index] = new Weather() : Weathers[index];
					weather.TemperatureCelsius = weatherInfo.getString(key);
				}
				else if(key.matches("tempF\\d")) {
					int index = Integer.parseInt(key.substring(5)) - 1;
					Weather weather = Weathers[index] == null ? Weathers[index] = new Weather() : Weathers[index];
					weather.TemperatureFahrenheit = weatherInfo.getString(key);
				}
				else if(key.matches("weather\\d")) {
					int index = Integer.parseInt(key.substring(7)) - 1;
					Weather weather = Weathers[index] == null ? Weathers[index] = new Weather() : Weathers[index];
					weather.Weather = weatherInfo.getString(key);
				}
				else if(key.matches("img_title\\d+")) {
					int index = (Integer.parseInt(key.substring(9)) - 1) / 2;
					Weather weather = Weathers[index] == null ? Weathers[index] = new Weather() : Weathers[index];
					int weatherCode = Constants.FindWeatherCode(weatherInfo.getString(key));
					weather.WeatherIconURI = Utils.WrapNetworkImageUri(context, "http://www.weather.com.cn/m/i/icon_weather/42x30/d" + (weatherCode < 10 ? "0" + weatherCode + "" : weatherCode + "") + ".gif");
				}
				else if(key.matches("wind\\d")) {
					int index = Integer.parseInt(key.substring(4)) - 1;
					Weather weather = Weathers[index] == null ? Weathers[index] = new Weather() : Weathers[index];
					weather.Wind = weatherInfo.getString(key);
				}
			
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}
